﻿using SelfManagement.Database.POCO;
using SelfManagement.IServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SelfManagement.Utility.Extensions;
using Ninject;

namespace SelfManagement.Services
{
    public class DailyService: BaseService<Daily>, IDailyService
    {
        [Inject]
        public IBaseService<DailyTask> DailyTaskService { get; set; }
        /// <summary>
        /// 日报
        /// </summary>
        /// <param name="uid">用户id</param>
        /// <param name="dailyId">日常</param>
        /// <returns></returns>
        public Daily GetUserDaily(string uid, string dailyId)
        {
            return Get(d => d.User_Id == uid && d.Id == dailyId && !d.IsDelete);
        }


        /// <summary>
        /// 查询用户的日常任务
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public IQueryable<Daily> QueryUserDailies(string uid)
        {
            return Query(d => d.User_Id == uid)
                        .Where(d => !d.IsDelete);
        }


        /// <summary>
        /// 今日
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public Daily GetUserToday(string uid)
        {
            var today = DateTime.Now.Date;
            return QueryUserDailies(uid).Where(t => t.Date == today).FirstOrDefault();
        }


        /// <summary>
        /// 查询是否已存在某日的计划
        /// </summary>
        /// <param name="daily"></param>
        /// <returns></returns>
        public bool IsExistDateOfDaily(string dailyId, string uid, DateTime date)
        {
            var exist = QueryUserDailies(uid).Where(d => d.Date == date).FirstOrDefault();
            return exist.IsNotNull() && exist.Id != dailyId;
        }


        /// <summary>
        /// 删除用户的日计划
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteUserDailyById(string uid, string id)
        {
            Daily daily = GetUserDaily(uid, id);
            if(daily.IsNull())
            {
                return false;
            }
            
            string[] dailyTaskIds = daily.Tasks.Select(t => t.Id).ToArray();
            bool isDelete = Delete(daily);
            DailyTaskService.DeleteBatch(t => dailyTaskIds.Contains(t.Id)); // 清理无用的子任务
            return isDelete;
        }
    }
}
